package com.quectel.core.module.partybuildingsurvey.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.global.SqlConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.partybuilding.dto.PartyPersonDto;
import com.quectel.core.module.partybuilding.service.PartyPersonService;
import com.quectel.core.module.partybuildingsurvey.dao.PartySurveyPersonRecordDao;
import com.quectel.core.module.partybuildingsurvey.dto.PartySurveyPersonAnswerDto;
import com.quectel.core.module.partybuildingsurvey.dto.PartySurveyPersonBindingDto;
import com.quectel.core.module.partybuildingsurvey.dto.PartySurveyPersonRecordDto;
import com.quectel.core.module.partybuildingsurvey.entity.PartySurveyPersonRecordEntity;
import com.quectel.core.module.partybuildingsurvey.service.PartySurveyPersonAnswerService;
import com.quectel.core.module.partybuildingsurvey.service.PartySurveyPersonBindingService;
import com.quectel.core.module.partybuildingsurvey.service.PartySurveyPersonRecordService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
/**
 *
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/06/19 15:25
 */
@DubboService
public class PartySurveyPersonRecordServiceImpl implements PartySurveyPersonRecordService{

    private static final Logger LOGGER = LoggerFactory.getLogger(PartySurveyPersonRecordServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> PARTY_SURVEY_PERSON_RECORD_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "PARTY_SURVEY_PERSON_RECORD_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<PartySurveyPersonRecordDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(PARTY_SURVEY_PERSON_RECORD_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };
    @Autowired
    private PartySurveyPersonBindingService partySurveyPersonBindingService;
    @Autowired
    private PartySurveyPersonRecordDao partySurveyPersonRecordDao;
    @Autowired
    private PartySurveyPersonAnswerService partySurveyPersonAnswerService;
    @Autowired
    private PartyPersonService partyPersonService;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Long submit(PartySurveyPersonRecordDto dto){
        Long save = save(dto);
        dto.setId(save);
        //修改是否参加
        PartySurveyPersonBindingDto partySurveyPersonBindingDto = partySurveyPersonBindingService.selectBySurveyIdAndPersonId(dto.getPartySurveyId(), dto.getPersonId());
        if(partySurveyPersonBindingDto!=null){
            partySurveyPersonBindingDto.setParticipateStatus(SystemConstants.YES);
            partySurveyPersonBindingDto.setParticipateTime(new Date());
            partySurveyPersonBindingDto.setAnonymous(dto.getAnonymous());
            partySurveyPersonBindingService.updateById(partySurveyPersonBindingDto);
        }

        if(CollectionUtils.isNotEmpty(dto.getPersonAnswerList())){
            List<PartySurveyPersonAnswerDto> personAnswerList = dto.getPersonAnswerList();
            for (PartySurveyPersonAnswerDto answerDto: personAnswerList){
                answerDto.setRecordId(dto.getId());
                answerDto.setCreateTime(new Date());
                partySurveyPersonAnswerService.save(answerDto);
            }
        }

        return save;
    }


    @Override
    public PartySurveyPersonRecordDto selectLastBySurveyIdAndPersonId(Long surveyId, Long personId) {
        PartySurveyPersonRecordEntity entity = partySurveyPersonRecordDao.selectOne(new LambdaQueryWrapper<PartySurveyPersonRecordEntity>()
                .eq(PartySurveyPersonRecordEntity::getPartySurveyId, surveyId)
                .eq(PartySurveyPersonRecordEntity::getPersonId, personId)
                .orderBy(Boolean.TRUE,Boolean.FALSE,PartySurveyPersonRecordEntity::getId)
                .last(SqlConstants.MYSQL_LIMIT_ONE)

        );
        PartySurveyPersonRecordDto partySurveyPersonRecordDto = paddingField(CopyUtils.copyObj(entity, PartySurveyPersonRecordDto.class));
        return partySurveyPersonRecordDto;
    }

    @Override
    public List<PartySurveyPersonRecordDto> selectBySurveyIdAndPersonId(Long surveyId, Long personId) {
        List<PartySurveyPersonRecordEntity> list = partySurveyPersonRecordDao.selectList(new LambdaQueryWrapper<PartySurveyPersonRecordEntity>()
                .eq(PartySurveyPersonRecordEntity::getPartySurveyId, surveyId)
                .eq(PartySurveyPersonRecordEntity::getPersonId, personId));
        List<PartySurveyPersonRecordDto> result = CopyUtils.copyList(list, PartySurveyPersonRecordDto.class);
        return result;
    }


    @Override
    public PartySurveyPersonRecordDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                PARTY_SURVEY_PERSON_RECORD_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public PartySurveyPersonRecordDto selectById(Long id){
            PartySurveyPersonRecordEntity entity = partySurveyPersonRecordDao.selectById(id);
        PartySurveyPersonRecordDto partySurveyPersonRecordDto = paddingField(CopyUtils.copyObj(entity, PartySurveyPersonRecordDto.class));

        return partySurveyPersonRecordDto;
    }

    @Override
    public List<PartySurveyPersonRecordDto> queryList(Map<String,Object> params){
        List<PartySurveyPersonRecordEntity> list = partySurveyPersonRecordDao.queryList(params);
        List<PartySurveyPersonRecordDto> result =  CopyUtils.copyList(list,PartySurveyPersonRecordDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    @Override
    public List<PartySurveyPersonRecordDto> queryListWithoutPadding(Map<String,Object> params){
        List<PartySurveyPersonRecordEntity> list = partySurveyPersonRecordDao.queryList(params);
        return CopyUtils.copyList(list,PartySurveyPersonRecordDto.class);
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private PartySurveyPersonRecordDto paddingField(PartySurveyPersonRecordDto dto){
        if (dto != null){
            if(SystemConstants.YES.equals(dto.getAnonymous())){
                dto.setPersonName("匿名");
                dto.setPersonMobile("");
            }else{
                PartyPersonDto partyPersonDto = partyPersonService.selectCacheById(dto.getPersonId());
                if(partyPersonDto!=null){
                    dto.setPersonName(partyPersonDto.getName());
                    dto.setPersonMobile(partyPersonDto.getMobile());
                }
            }

        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params){
        return partySurveyPersonRecordDao.queryTotal(params);
    }

    @Override
    public Long save(PartySurveyPersonRecordDto dto){
        PartySurveyPersonRecordEntity entity = CopyUtils.copyObj(dto,PartySurveyPersonRecordEntity.class);
        entity.setId(Snowflake.nextId());
        partySurveyPersonRecordDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(PartySurveyPersonRecordDto dto){
        PartySurveyPersonRecordEntity entity = CopyUtils.copyObj(dto,PartySurveyPersonRecordEntity.class);

        partySurveyPersonRecordDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(PartySurveyPersonRecordDto dto) {
       PartySurveyPersonRecordEntity entity = CopyUtils.copyObj(dto,PartySurveyPersonRecordEntity.class);

       MyBatisPlusUtils.updateAllColumnById(entity, partySurveyPersonRecordDao);

       CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id){

        CLEAR_CACHE_FUNC.accept(selectById(id));

        partySurveyPersonRecordDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids){
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
